package com.haha.community.controller;

import com.google.code.kaptcha.Producer;
import com.haha.community.entity.User;
import com.haha.community.service.UserService;
import com.haha.community.util.ActivationStatus;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private Producer kaptchaProduce;

    //进行注册相关
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String getRegister() {
        //因为是动态页面，所以不能直接请求，需要经过控制层
        return "/site/register";
    }
    //登录请求
    //这个方法的目的是返回一个完整的html
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String getlogin() {
        //因为是动态页面，所以不能直接请求，需要经过控制层
        return "/site/login";
    }

    //表单注册
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String handleRegister(Model model, User user) {
        Map<String, Object> map = userService.register(user);
        if (map.get("msg") == null) {
            model.addAttribute("msg", "注册成功，请注意在邮箱中查收进行激活");
            model.addAttribute("target", "index");
            return "site/operate-result";
        } else {
            String msg = (String) map.get("msg");
            model.addAttribute("msg", msg);
            return "site/register";
        }
    }

    //进行邮箱激活的处理
    @RequestMapping(path = "/activation/{id}/{code}", method = RequestMethod.GET)
    public String handleEmail(Model model, @PathVariable("id") int id, @PathVariable("code") String activationCode) {
        int result = userService.handleActivation(id, activationCode);
        if (result == ActivationStatus.ACTIVATION_SUCESS) {
            model.addAttribute("msg", "激活成功，账号可以正常使用了");
            model.addAttribute("target", "/login");
        } else if (result == ActivationStatus.ACTIVATION_REPEAT) {
            model.addAttribute("msg", "已经激活过了，不要重复激活，请去登录");
            model.addAttribute("target", "/login");
        } else {
            model.addAttribute("msg", "相关参数被更改，激活失败，请用原链接进行激活");
            model.addAttribute("target", "/index");
        }
        return "site/operate-result";
    }

    //进行验证码的处理
    @RequestMapping(value = "/kaptcha", method = RequestMethod.GET)
    public void getImage(HttpServletResponse response, HttpSession session) {
        String text = kaptchaProduce.createText();
        session.setAttribute("kaptcha", text);
        BufferedImage image = kaptchaProduce.createImage(text);
        //将图片输出给浏览器
        response.setContentType("image/png");

        try {
            //运用图片处理工具进行
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            logger.error("输出验证码错误");
        }
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String handleLogin(HttpSession session, HttpServletResponse response, Model model,
                              String username, String password, String kaptcha, @RequestParam(required = false,defaultValue = "off") String isRemeber) {

        String kaptcha1 = (String) session.getAttribute("kaptcha");
        //进行验证码的验证
        if (StringUtils.isAnyBlank(kaptcha) || !StringUtils.equalsIgnoreCase(kaptcha1, kaptcha)) {
            model.addAttribute("msg", "输入正确的验证码");
            return "/site/login";
        }
        //在工具类中定义时间常量
        int expired = "on".equals(isRemeber) ? ActivationStatus.REMEBER_TIME : ActivationStatus.DEFALUT_TIME;
        Map<String, Object> map = userService.handleLogin(username, password, expired);
        if (map.get("ticket") == null) {
            //说明此时出现了错误
            String msg = (String) map.get("msg");
            model.addAttribute("msg", msg);
            return "/site/login";
        }
        String ticket = (String) map.get("ticket");
        //登录成功下发一个cookie
        Cookie cookie = new Cookie("ticket", ticket);
        cookie.setMaxAge(expired);
        response.addCookie(cookie);
        //跳转到首页
        return "redirect:/index";
    }
    @RequestMapping("logout")
    public String logout(@CookieValue("ticket")String ticket){
        userService.logout(ticket);
        return "redirect:/login";
    }

}
